package com.wpp;

import org.junit.Test;

import java.io.*;

/*
 * 缓冲流：提高流的读写速度的
 *提高读写速度的原因：内部提供了一个缓冲区；
 *
 *
 *
 * */
public class BufferedIOStream {


    @Test
    public void test() {
        long startTime = System.currentTimeMillis();
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;

        try {

            //造文件对象
            File file = new File("F:\\Java测试源代码\\day10-IO流\\hello.txt");
            File file1 = new File("F:\\Java测试源代码\\day10-IO流\\hello3.txt");
            //造节点流
            FileReader fis = new FileReader(file);
            FileWriter fos = new FileWriter(file1);
            //造缓冲流
            bufferedReader = new BufferedReader(fis);
            bufferedWriter = new BufferedWriter(fos);

            char[] chars = new char[5];
            int len;
            while ((len = bufferedReader.read(chars)) != -1) {
                bufferedWriter.write(chars, 0, len);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //因为外层流关闭会自动关闭内层流。所在在此只需要关闭外层流即可
            if (bufferedReader != null) {

                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {

                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        //缓冲流，节点流对比
        long startTime1 = System.currentTimeMillis();
        FileReader fis = null;
        FileWriter fos = null;
        try {

            //造文件对象
            File file = new File("F:\\Java测试源代码\\day10-IO流\\hello.txt");
            File file1 = new File("F:\\Java测试源代码\\day10-IO流\\hello2.txt");
            //造节点流
            fis = new FileReader(file);
            fos = new FileWriter(file1);


            char[] chars = new char[5];
            int len;
            while ((len = fis.read(chars)) != -1) {
                fos.write(chars, 0, len);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //因为外层流关闭会自动关闭内层流。所在在此只需要关闭外层流即可
            if (fis != null) {

                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {

                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long endTime1 = System.currentTimeMillis();


        long l = endTime - startTime;
        long l1 = endTime1 - startTime1;

        System.out.println("缓冲流" + l);
        System.out.println("节点流" + l1);
    }
}
